package server;

import catalina.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.base.HttpServlet;
import server.base.HttpResponse;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName TomcatContainer
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/3/5
 * @Version 1.0.0
 */
public class TomcatContainer {

    private Server server= new StanderServer();

    private Mapper mapper = new Mapper();

    public void start() {
        try{
            int port = init();
//            loadConfig();
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true){

            // 1.0 Mincat
           /* Socket accept = serverSocket.accept();
            OutputStream outputStream = accept.getOutputStream();
            String data = "Hello world!";
            String header = HttpResponseUtil.getHttpHeader200(data.getBytes().length);
            String content = header + data;
            outputStream.write(content.getBytes());*/

           // 2.0 Mincat
       /*     Socket accept = serverSocket.accept();
            InputStream inputStream = accept.getInputStream();
            //封装Request对象
            Request request = new Request(inputStream);

            //封装返回对象Response
            Response response = new Response(accept.getOutputStream());
            response.outputHtml(request.getUrl());
            accept.close();*/

            //3.0实现动态访问（直接访问servlet）和静态两种
//            Socket accept = serverSocket.accept();
//            InputStream inputStream = accept.getInputStream();
//            //封装Request对象
//            Request request = new Request(inputStream);
//
//            //封装返回对象Response
//            Response response = new Response(accept.getOutputStream());
//
//            if(map.get(request.getUrl()) == null){
//                response.outputHtml(request.getUrl());
//            }else{
//                server.service(request,response);
//            }
//            accept.close();

            //4.0 实现运行webapps下的多项目
            Socket accept = serverSocket.accept();
            InputStream inputStream = accept.getInputStream();
            //封装Request对象
            Request request = new Request(inputStream);

            //封装返回对象Response
            Response response = new Response(accept.getOutputStream());

            //定位servlet
            mapper.map(request);
            //层级调用
            server.service(request,response);
            accept.close();


        }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int init() {
        int port = 8080;
        StanderService standerService = new StanderService();
        ((StanderServer) server).setService(standerService);
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(resourceAsStream);
            //获取跟节点 server
            Element rootElement = read.getRootElement();

            List<Element> servletNodes = rootElement.selectNodes("//Service");
            for (Element servletNode : servletNodes) {
                //设置connector
                Element node = (Element) servletNode.selectSingleNode("Connector");
                port =  Integer.parseInt(node.attributeValue("port"));
                Connector connector = new Connector(port);
                standerService.setConnector(connector);

                //设置engine
                StandardEngine standardEngine = new StandardEngine();
                standerService.setEngine(standardEngine);
                //设置host
                List<Element> listHost = servletNode.selectNodes("//Host");
                for (Element element : listHost) {
                    String name = element.attributeValue("name");
                    String appBase = element.attributeValue("appBase");
                    Mapper.MappedHost mappedHost = mapper.addHost(name, appBase);
                    //设置context
                    List<Element> listContext = element.selectNodes("//Context");
                    for (Element contextEle : listContext) {
                        String docBase = contextEle.attributeValue("docBase");
                        String path = contextEle.attributeValue("path");
                        Mapper.MappedContext mappedContext = mappedHost.contextList.addContext(docBase, path);
                        //封装设置wrapper
                        new WebAppsParse().parse(mappedContext,appBase);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return port;
    }

}
